package org.inspursc.s0517.health.common.security;

import org.inspursc.s0517.health.common.dao.SysRoleDao;
import org.inspursc.s0517.health.common.dao.SysRoleUserDao;
import org.inspursc.s0517.health.common.dao.SysUserDao;
import org.inspursc.s0517.health.common.entity.SysRole;
import org.inspursc.s0517.health.common.entity.SysRoleUser;
import org.inspursc.s0517.health.common.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CustomUserService implements UserDetailsService {


    @Autowired
    private SysUserDao userDao;

    @Autowired
    private SysRoleUserDao roleUserDao;

    @Autowired
    private SysRoleDao roleDao;

    @Autowired
    private SessionRegistry sessionRegistry;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userDao.findByUsername(username);
        if (user != null) {
            if (user.getStatus() == 1) {
                //用户已经登录则此次登录失败
                List<Object> o = sessionRegistry.getAllPrincipals();

                for (Object principal : o) {
                    if (principal instanceof SysUser && (user.getUsername().equals(((SysUser) principal).getUsername()))) {
                        throw new SessionAuthenticationException("用户[" + username + "]已经在线，登录失败！！！");
                    }
                }
                List<SysRoleUser> sysRoleUsers = roleUserDao.findBySysUserId(user.getId());
                List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                for (SysRoleUser roleUser : sysRoleUsers) {
                    SysRole role = roleDao.getOne(roleUser.getSysRoleId());
                    if (role != null && role.getName() != null) {
                        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getName());
                        //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                        grantedAuthorities.add(grantedAuthority);
                    }
                }
                user.setGrantedAuthorities(grantedAuthorities);
                return user;
            }
            throw new UsernameNotFoundException("用户: " + username + " 已被禁用，不允许登陆，请联系管理员!");
        } else {
            throw new UsernameNotFoundException("用户: " + username + " 不存在!");
        }
    }
}
